﻿using System.IO;
using System.Text;

namespace YPF.Common.Utf8编码转换
{
    public static class ConvertToUtf8
    {
        /// <summary>
        /// 将字符串转uft8编码格式字符串
        /// </summary>
        /// <param name="str">源字符串</param>
        /// <returns></returns>
        public static string GetUtf8ByString(string str)
        {
            if (!string.IsNullOrEmpty(str))
            {
                var bytes = Encoding.UTF8.GetBytes(str);
                return Encoding.UTF8.GetString(bytes);
            }
            else
            {
                return null;
            }

        }

        /// <summary>
        /// 将文本转uft8编码格式字符串
        /// </summary>
        /// <param name="path">文件路径</param>
        /// <returns></returns>
        public static string GetUtf8ByPath(string path)
        {
            if (!string.IsNullOrEmpty(path))
            {
                var str = File.ReadAllText(path, Encoding.Default);
                return GetUtf8ByString(str);
            }
            else
            {
                return null;
            }
        }

        /// <summary>
        /// 将byte[]转为utf8编码格式字符串
        /// </summary>
        /// <param name="bytes">源byte[]</param>
        /// <returns></returns>
        public static string GetUtf8ByBytes(byte[] bytes)
        {
            if (bytes.Length > 0)
            {
                return Encoding.UTF8.GetString(bytes);
            }
            else
            {
                return null;
            }
        }
    }
}
